package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/*文件上传下载*/
@Slf4j
@RestController
@RequestMapping("/common")
public class FileUpController {
    @Value("${reggie.path}")
    private String basePath;
    @PostMapping("/upload")
    public R<String> imgupload(MultipartFile file){
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //需要获取文件名的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //用UUID给这个文件命名防止出现重复，再把获取的后缀拼接上
        String uuid = UUID.randomUUID().toString()+substring;
        //创建文件夹用来放文件
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdir();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + uuid));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(uuid);
    }
    @GetMapping("/download")
    public void imgDownload(String name, HttpServletResponse response){
        try {
            //从本地获取文件
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));
            //获取的文件发送给浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //判断类型
            response.setContentType("image/jpeg");
            //读取文件
            int len=0;
            byte[] bytes=new byte[1024];
            while((len=fileInputStream.read(bytes))!=-1){
                //读到的文件写回前端
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
